<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\AdminController as Controller;
use Illuminate\Http\Request; 
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use App\Services\OSS;
class UploadController extends Controller
{
    public function __construct(){
        #parent::__construct();
        
    }
    
    public function __invoke(){
        return $this->index(func_get_args());
    }


    /*
    上传的后台只需要返回一个 JSON 数据，结构如下：
    {
        success : 0 | 1,           // 0 表示上传失败，1 表示上传成功
        message : "提示的信息，上传成功或上传失败及错误信息等。",
        url     : "图片地址"        // 上传成功时才返回
    }
    */
    public function uploadmd(Request $request){
        $admin = session('admin');
        if( empty($admin['id']) ){
        }

        $data=$request->input();
         $pic=$request->file('editormd-image-file');
         $name=$pic->getClientOriginalName();//得到图片名；
         $ext=$pic->getClientOriginalExtension();//得到图片后缀；
         $fileName=md5(uniqid($name));
         $fileName=$fileName.'.'.$ext;//生成新的的文件名
         $bool=Storage::disk('public')->put($fileName,file_get_contents($pic->getRealPath()));//
         if($bool){
            die(json_encode([
                    'success'=>1,
                    'url'=>'/storage/'.$fileName,
                ]));
         }else{
            die(json_encode([
                    'success'=>0,
                    'message'=>'fail',
                ]));
         }
    }
    
    public function webupload(Request $request){
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        $admin = session('admin');
        if( empty($admin['id']) ){
            die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Please Login."}, "id" : "id"}');
        }
        // Support CORS
        // header("Access-Control-Allow-Origin: *");
        // other CORS headers if any...
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }
        if ( !empty($_REQUEST[ 'debug' ]) ) {
            $random = rand(0, intval($_REQUEST[ 'debug' ]) );
            if ( $random === 0 ) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }
        // header("HTTP/1.0 500 Internal Server Error");
        // exit;
        // 5 minutes execution time
        @set_time_limit(5 * 60);
        // Uncomment this one to fake upload time
        // usleep(5000);
        // Settings
        // $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        #!is_dir(public_path('storage/up')) && mkdir(public_path('storage/up'));
        #!is_dir(public_path('storage/up').'/upload_tmp') && mkdir(public_path('storage/up').'/upload_tmp');
        #!is_dir(public_path('storage/up').'/article/'.date('Ymd')) && mkdir(public_path('storage/up').'/article/'.date('Ymd'));
        $targetDir = public_path('storage/up').'/upload_tmp';
        $uploadDir = public_path('storage/up').'/thumb/'.date('Ymd');
        if(!is_dir($uploadDir)){
            @mkdir($uploadDir,0777,true);
        }
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds

        // Create target dir
        if (!is_dir($targetDir)) {
            @mkdir($targetDir,0777,true);
        }

        // Get a file name
        $fileName = uniqid("file_").'.jpg';

        $filePath = $targetDir . '/' . $fileName;
        $uploadPath = $uploadDir . '/' . $fileName;

        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;

        // Remove old temp files
        if ($cleanupTargetDir) {

            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }

        // Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
        if ( $done ) {
       
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
        }
        $url =  str_replace(public_path(), '', $uploadPath);
        $url = ltrim($url,'\\');

        #Oss
        $osspath = config('app')['env']=='production'?'Product/':'ceshi/Product/';
        OSS::upload($osspath.$fileName, $uploadPath);
        $url =OSS::getPublicUrl($osspath.$fileName);

        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id", "url" : "'.$url.'"}');
    }

    public function uploadck5(Request $request){
        $ck = request()->get('CKEditorFuncNum');
        if (request()->hasFile('upload')) {     //upload为ckeditor默认的file提交ID
            $file = request()->file('upload');   //从请求数据内容中取出图片的内容
            $allowed_extensions = ["png", "jpg", "gif","jpeg"]; //允许的图片后缀
            if ($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
                return '图片后缀只支持png,jpg,gif,请检查！';
            }
            $destinationPath = public_path('storage/up').'/Product';  //图片存放路径
            if(!is_dir($destinationPath)){
                @mkdir($destinationPath,0777,true);
            }
            $extension = $file->getClientOriginalExtension();  //获得文件后缀
            $fileName = order_no() . '.' . $extension;  //创建图片名字
            $result = $file->move($destinationPath, $fileName); //存储图片到路径
            $url = $destinationPath . '/' . $fileName; //输出图片网站中浏览路径
            #$url =  str_replace(public_path(), '', $url);
            #$url = DIRECTORY_SEPARATOR.ltrim($url,DIRECTORY_SEPARATOR);
            #OSS
            $osspath = config('app')['env']=='production'?'Product/':'ceshi/Product/';
            OSS::upload($osspath.$fileName, $url);
            $url =OSS::getPublicUrl($osspath.$fileName);
            return [
                "uploaded" => $url,
                "fileName" => $fileName,
                "url" => $url,
                "error" => [
                    "message" =>''
                ]
            ];
        }
    }

    public function aliyunoss(){
        dd( OSS::deleteObject('http://chuangkun.oss-cn-hangzhou.aliyuncs.com/ceshi/Product/logo.png') );
        $path = public_path('storage/up').'/goods/';
        if(!is_dir($path)){
            @mkdir($path,0777,true);
        }
        $file = $path.'logo.png';
        $osspath = config('app')['env']=='production'?'Product/':'ceshi/Product/';
        $bool = OSS::upload($osspath.'logo.png', $file); // 上传一个文件
        echo OSS::getPublicUrl($osspath.'logo.png'); // 打印出某个文件的外网链接
    }
}
